package com.haierCamera.customapplication.ui.login;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.Constants;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.repo.RegisterRepo;
import com.haierCamera.customapplication.api.vo.GetUserInfoResponse;
import com.haierCamera.customapplication.api.vo.LoginResponse;
import com.haierCamera.customapplication.api.vo.TXOauth;
import com.haierCamera.customapplication.common.Resource;
import com.haierCamera.customapplication.databinding.HzklActivityLoginBinding;

import com.haierCamera.customapplication.ui.MainActivity;
import com.haierCamera.customapplication.utils.AppManager;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.haierCamera.customapplication.utils.android.SystemUIHelper;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import javax.inject.Inject;

import dagger.Lazy;

public class HZKLLoginActivity extends BaseActivity {
    private HzklActivityLoginBinding binding;
    @Inject
    RegisterRepo repo;
    private IWXAPI api;
    @Inject
    Lazy<HttpErrorProcess> errorProcessLazy;
    private static final String PWD_MATCH = "^(1+[3,4,5,6,7,8,9])+\\d{9}";
    ////密码只包含字母，数字，字符中至少两种
    private static final String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{8,32}$";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SystemUIHelper.setFullWindowNew(getWindow());
        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_login);
        initData();
    }

    private void initData() {
        api = WXAPIFactory.createWXAPI(this, Constants.WeiXiID, false);
        api.registerApp(Constants.WeiXiID);
        binding.loginPwdLayout.setPasswordVisibilityToggleDrawable(R.drawable.hzkl_pwd_selector);
        binding.loginRegister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        binding.loginRegister.getPaint().setAntiAlias(true);//抗锯齿
        binding.loginRegister.setOnClickListener(view -> startActivity(new Intent(HZKLLoginActivity.this, HZKLRegisterActivity.class)));
        binding.loginForget.setOnClickListener(view -> startActivity(new Intent(HZKLLoginActivity.this, HZKLForgetActivity.class)));
        binding.loginBtn.setOnClickListener(view -> lgoin());
        binding.loginWX.setOnClickListener(view -> requestWeiXi());
        binding.loginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pwd = binding.loginPwd.getText().toString();
                if (!TextUtils.isEmpty(pwd)) {
                    String phone = binding.loginPhone.getText().toString();
                    if (!phone.matches(PWD_MATCH)) {
                        binding.textError.setVisibility(View.VISIBLE);
                        binding.loginBtn.setEnabled(false);
                        setColorRed();
                    } else {
                        binding.textError.setVisibility(View.GONE);
                        binding.loginBtn.setEnabled(true);
                        setColorBlue();
                    }
                    return;
                }
                if (s.length() == 11) {
                    String phone = binding.loginPhone.getText().toString();
                    if (!phone.matches(PWD_MATCH)) {
                        setColorRed();
                        binding.textError.setVisibility(View.VISIBLE);
                    } else {
                        setColorBlue();
                        binding.textError.setVisibility(View.GONE);
                        if (TextUtils.isEmpty(binding.loginPwd.getText().toString())) {
                            binding.loginBtn.setEnabled(false);
                        } else {
                            binding.loginBtn.setEnabled(true);
                        }
                    }
                } else {
                    binding.loginBtn.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        binding.loginPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = binding.loginPhone.getText().toString();
                if (!TextUtils.isEmpty(phone)) {
                    if (phone.matches(PWD_MATCH)) {
                        setColorBlue();
                        binding.textError.setVisibility(View.GONE);
                    } else {
                        binding.textError.setVisibility(View.VISIBLE);
                        setColorRed();
                    }
                }
                if (!TextUtils.isEmpty(s) && phone.matches(PWD_MATCH)) {
                    binding.loginBtn.setEnabled(true);
                } else {
                    binding.loginBtn.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void setColorRed() {
        binding.loginIv.setImageResource(R.drawable.hzkl_login_red_phone);
        binding.loginPhone.setTextColor(getResources().getColor(R.color.hzkl_colorAccent));
        binding.line.setImageResource(R.color.hzkl_colorAccent);
    }

    private void setColorBlue() {
        binding.loginIv.setImageResource(R.drawable.hzkl_login_blue_phone);
        binding.loginPhone.setTextColor(getResources().getColor(R.color.HZKLcolorAccent));
        binding.line.setImageResource(R.color.HZKLcolorAccent);
    }

    private void pwdColorRed() {
        binding.loginIv1.setImageResource(R.drawable.hzkl_login_red_pwd);
        binding.loginPwd.setTextColor(getResources().getColor(R.color.hzkl_colorAccent));
        binding.line1.setImageResource(R.color.hzkl_colorAccent);
    }

    private void pwdColorBlue() {
        binding.loginIv1.setImageResource(R.drawable.hzkl_login_blue_pwd);
        binding.loginPwd.setTextColor(getResources().getColor(R.color.HZKLcolorAccent));
        binding.line1.setImageResource(R.color.HZKLcolorAccent);
    }

    private void lgoin() {
        String phone = binding.loginPhone.getText().toString();
        String pwd = binding.loginPwd.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!pwd.matches(regex)) {
            pwdColorRed();
            binding.pwdError.setVisibility(View.VISIBLE);
            return;
        } else {
            pwdColorBlue();
            binding.pwdError.setVisibility(View.GONE);
        }
        repo.login(phone, pwd).observe(this, objectResource -> {
            switch (objectResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    Toast.makeText(HZKLLoginActivity.this, objectResource.errorMessage, Toast.LENGTH_SHORT).show();
                    break;
                case SUCCESS:
                    LoginResponse data = objectResource.data;
                    assert data != null;
                    Log.i("TAG", "user-Token-" + data.token);
                    SharedPreferencesUtils.saveString(Constants.SP_USER_TOKEN, data.token);
                    getUser();
                    break;
            }
        });
    }

    private void getUser() {
        repo.getUserInfo().observe(this, getUserInfoResource -> {
            switch (getUserInfoResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    break;
                case SUCCESS:
                    GetUserInfoResponse data = getUserInfoResource.data;
                    assert data != null;
                    if (TextUtils.isEmpty(data.nickName)) {
//                        binding.phone.setText(data.mobile);
                        SharedPreferencesUtils.saveString(Constants.SP_USER_PHONE, data.mobile);
                    } else {
//                        binding.phone.setText(data.nickName);
                        SharedPreferencesUtils.saveString(Constants.SP_USER_PHONE, data.nickName);
                    }
                    SharedPreferencesUtils.saveString(Constants.SP_USER_HEAD_URL, data.headUrl);

                    startActivity(new Intent(HZKLLoginActivity.this, MainActivity.class));
                    finish();
                    AppManager.getAppManager().finishAllActivity();
//                    Glide.with(this).load(data.headUrl).apply(new RequestOptions().circleCrop()).into(binding.userIcon);
                    break;
            }
        });
    }

    private void requestWeiXi() {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(HZKLLoginActivity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
        } else {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test";
            api.sendReq(req);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String info = SharedPreferencesUtils.getString(Constants.WeiXi_USER_INFO, "");
        String openId = SharedPreferencesUtils.getString(Constants.WeiXi_USER_OPENID, "");
        if (TextUtils.isEmpty(info)) {
            return;
        }
        showLoadingDialog();
        try {
            JSONObject jsonObject = new JSONObject(info);
            String nickname = jsonObject.getString("nickname");
            String headimgurl = jsonObject.getString("headimgurl");
            registerWX(nickname, headimgurl, openId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        SharedPreferencesUtils.removeSync(Constants.WeiXi_USER_INFO);
        SharedPreferencesUtils.removeSync(Constants.WeiXi_USER_OPENID);
    }

    private void registerWX(String nickname, String headimgurl, String openId) {
        repo.oauth("0", openId, nickname, headimgurl).observe(this, txOauthResource -> {
            switch (txOauthResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    errorProcessLazy.get().process(txOauthResource);
                    dismissLoadingDialog();
                    break;
                case SUCCESS:
                    TXOauth data = txOauthResource.data;
                    //是否绑定账户 true=需要绑定 false=不需要绑定并取token字段
                    new Handler().postDelayed(() -> {
                        dismissLoadingDialog();
                        assert data != null;
                        if (data.flag) {
                            startActivityForResult(new Intent(HZKLLoginActivity.this, HZKLWXphoneActivity.class).putExtra("openId", openId), 100);
                        } else {
                            getUser();
                            SharedPreferencesUtils.saveString(Constants.SP_USER_TOKEN, data.token);
                            //startActivity(new Intent(HZKLLoginActivity.this, MainActivity.class));
                        }
                    }, 1000);
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            finish();
        }
    }
}
